﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar.Entity;
using RuoVea.ExSugar.UnitOfWork;
using RuoVea.ExUtil;
using RuoVea.OmiApi.Dict.Service;
using RuoVea.OmiApi.Reports.Dto;
using RuoVea.OmiApi.Reports.Models;
using RuoVea.OmiApi.Reports.Service;
using RuoVea.OmiApi.Reports.Util;
using RuoVea.OmiReports.Attributes;
using SqlSugar;

namespace RuoVea.OmiReports.Controllers;

/// <summary>
/// 
/// </summary>
[AppRoute]
public class RptSqlController : Controller
{
    /// <summary>
    /// 
    /// </summary>
    private readonly RptSqlService _rptSqlService;
    private readonly RptDatabaseService _RptDatabaseService;
    private readonly SysDictTypeService _sysDictTypeService;
    private readonly RptSqlColumnService _ReportSqlColumnService;


    /// <summary>
    /// 
    /// </summary>
    /// <param name="rptSqlService"></param>
    /// <param name="rptDatabaseService"></param>
    /// <param name="reportSqlColumnService"></param>
    /// <param name="sysDictTypeService"></param>
    public RptSqlController(RptSqlService rptSqlService, RptDatabaseService rptDatabaseService, RptSqlColumnService reportSqlColumnService, SysDictTypeService sysDictTypeService)
    {
        _rptSqlService = rptSqlService;
        _RptDatabaseService = rptDatabaseService;
        _ReportSqlColumnService = reportSqlColumnService;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpGet(nameof(Index))]
    public IActionResult Index()
    {
        return View();
    }

    /// <summary>
    /// 查询字典
    /// </summary>
    /// <returns></returns>
    [HttpGet("dictlist")]
    public async Task<RestfulResult> GetDictList()
    {
        var dicts = await _sysDictTypeService.GetDataList();
        var dictsList = dicts.Select(x => new { value = x.Code, label = x.Name }).ToList();
        return Restful.Success(dictsList);
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("pages")]
    public async Task<RestfulResult<PageResult<RptSql>>> GetPagesAsync()
    {
        using var sr = new StreamReader(Request.Body);
        string dataStr = await sr.ReadToEndAsync();
        if (Request.Body.CanSeek)
            Request.Body.Position = 0;
        //if (string.IsNullOrWhiteSpace(dataStr))
        //    throw new Exception(i18n.upload_data_required);
        RptSqlParam data = JsonConvert.DeserializeObject<RptSqlParam>(dataStr);
        data ??= new RptSqlParam { PageNo = 1, PageSize = 10 };

        var query = await _rptSqlService.GetPagesAsync(data);
        return query;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [HttpGet("Detail/{id}")]
    public RestfulResult<SqlDto> Detail(long id)
    {
        var restful = _rptSqlService.GetDetail(id);
        return restful;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [HttpPost("list")]
    public async Task<RestfulResult<PageResult<RptSql>>> GetlistAsync()
    {
        var restful = await _rptSqlService.GetlistAsync();
        return restful;
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    [HttpPost("add")]
    public async Task<RestfulResult> Add([FromBody] SqlDto data)
    {
        var restful = await _rptSqlService.AddAsync(data);
        return restful;
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("update")]
    public async Task<RestfulResult> Update([FromBody] SqlDto data)
    {
        var restful = await _rptSqlService.UpdateAsync(data);
        return restful;
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete("delete")]
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        var restful = await _rptSqlService.DeleteAsync(data);
        return restful;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("getbyid/{id}")]
    public RptSql GetDataById(long id)
    {
        return _rptSqlService.GetDataById(id);
    }

    /// <summary>
    /// 解析 SQL(SQL Server)
    /// </summary>
    /// <returns></returns>
    [HttpPost("parsesqltext")]
    public RestfulResult ParseSQLText([FromBody] RptSql parm)
    {
        try
        {
            RptDatabase dbConfig = _RptDatabaseService.GetDataById(parm.DatabaseId);
            using (var db = DbProvider.GetSugarDbContextBySelected(dbConfig.ConnectionString, dbConfig.DataType ?? 0))
            {
                return Restful.Success(_ReportSqlColumnService.GetReportMetaDataColumns(db, parm.QuerySql));
            }
        }
        catch (Exception ex)
        {
            return Restful.Bad(CodeStatus.BadRequest, ex.Message);
        }
    }

    /// <summary>
    /// 获取报表信息(主要包括列信息和布局配置)
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("getreportsqlinfo")]
    public RestfulResult GetReportSqlInfo([FromQuery] long id)
    {
        //RptSql reportSql = _rptSqlService.GetById(id);
        var reportSqlColumns = _ReportSqlColumnService.GetReportSqlColumn(id);
        return Restful.Success(reportSqlColumns);
    }
}